import { login as UniLogin } from '@uni-helper/uni-promises'
import type { UserDto } from '../api/user/type'
import { getAppletUserInfoAlipay, getAppletUserInfoWx, getUserInfo } from '@/api/user'
import globalVariable from '@/utils/globalVariable'

function useUser() {
    const isLogin = ref(false)

    const userInfo = ref<UserDto>({} as UserDto)

    const alipayOpenId = ref('')

    let waiting = true

    async function login() {
        await new Promise((resolve, reject) => {
            UniLogin({
                success: async (res) => {
                    let info
                    // #ifdef MP-ALIPAY
                    info = await getAppletUserInfoAlipay({
                        code: res.code,
                    })
                    alipayOpenId.value = info.openid
                    // #endif
                    // #ifdef MP-WEIXIN
                    info = await getAppletUserInfoWx({
                        appId: globalVariable.appId,
                        code: res.code,
                    })
                    // #endif
                    if (!info.token) {
                        waiting = false
                        return
                    }
                    globalVariable.token = info.token
                    const userData = await getUserInfo({
                        openId: info.openid,
                        platform: globalVariable.platForm === 'mp-alipay' ? 1 : 0,
                    })
                    if (userData) {
                        waiting = false
                        userInfo.value = userData
                        isLogin.value = true
                    }
                    resolve(true)
                },
                fail: () => {
                    waiting = false
                    reject(false)
                },
            })
        })
    }

    async function init() {
        isLogin.value = false
        userInfo.value = {} as UserDto
    }

    async function waitLogin() {
        await new Promise((resolve, reject) => {
            const interval = setInterval(() => {
                if (!waiting) {
                    clearInterval(interval)
                    if (userInfo.value.userId)
                        resolve(true)
                    else
                        reject(false)
                }
            }, 100)
        })
    }

    return {
        isLogin,
        login,
        waitLogin,
        userInfo,
        init,
        alipayOpenId,
    }
}

export default useUser()
